//
//  KRChatViewController.m
//  KingrayTone_ios
//
//  Created by XiongYingqi on 14-5-20.
//  Copyright (c) 2014年 XiongYingqi. All rights reserved.
//

#import "KRChatViewController.h"
#import "XMPPUserCoreDataStorageObject.h"
#import "KRAppDelegate.h"
#import "NSString+DDXML.h"
#import "UIBubbleTableView.h"
#import "DDLog.h"
#import "XMPPMessageArchiving_Message_CoreDataObject.h"
#import "KRChatViewControllerDelegate.h"


// Log levels: off, error, warn, info, verbose
#if DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
  static const int ddLogLevel = LOG_LEVEL_INFO;
#endif

@interface KRChatViewController ()

@end

@implementation KRChatViewController

/**
* 存储已经打开的实例
*/
static NSMapTable *chatRooms;

static IBOutlet id <KRChatViewControllerDelegate> delegate;


//int currentKeyBoardHeight;
//
//bool isFrameMove;



/**
* 打开与用户关联的聊天室，如果已经存在则获取已经存在的实例
*/
+ (id)getRoom:(XMPPUserCoreDataStorageObject *)withUser {
    if (chatRooms == nil) {
        chatRooms = [[NSMapTable alloc] init];
    }
    KRChatViewController *chatRoom = [chatRooms objectForKey:withUser];
    if (chatRoom == nil) {
        chatRoom = [[KRChatViewController alloc] initWithUser:withUser initWithNibName:nil bundle:nil];
        [chatRooms setObject:chatRoom forKey:withUser];
    }

//    NSLog(@"chatRoom: %d", chatRoom);
    return chatRoom;
}


- (id)initWithUser:(XMPPUserCoreDataStorageObject *)withUser initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.withUser = withUser;
        if (delegate) {
            [delegate chatViewOpened:self];
        }
//        self.jidLabel.text = xmppJid.user;
//        NSLog(@" -------- do --------- %d", self);
    }


//    NSLog(@" -------- init --------- %d", self);
    return self;
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

//        self.hidesBottomBarWhenPushed = YES;
        // Custom initialization
    }
    return self;
}

- (void)dealloc{
    [delegate chatViewClosed:self];
}

- (void)viewDidLoad {
    [self scrollToLast];

    self.navigationItem.title = self.withUser.displayName;

//    self.hidesBottomBarWhenPushed = true;
//    CGFloat *r = CGFLOAT_DEFINED;
//    CGFloat *g = CGFLOAT_DEFINED;
//    CGFloat *b = CGFLOAT_DEFINED;
//    CGFloat *a = CGFLOAT_DEFINED;
//    [self.sendMessageButton.tintColor getRed:r green:g blue:b alpha:a];
//    NSLog(@"r ====== %f", r);
//    NSLog(@"g ====== %f", g);
//    NSLog(@"b ====== %f", b);
//    NSLog(@"a ====== %f", a);

//    CGColorRef cgColor = self.sendMessageButton.tintColor.CGColor;
//
//    const CGFloat *components = CGColorGetComponents(cgColor);
//    NSLog(@"Red: %f", components[0]);
//    NSLog(@"Green: %f", components[1]);
//    NSLog(@"Blue: %f", components[2]);
//    NSLog(@"a: %f", components[3]);




//    if ([KRAppDelegate appDelegate].tabBarController.tabBar) {
//
//        CGFloat height = CGRectGetHeight([KRAppDelegate appDelegate].tabBarController.tabBar.frame);
//        CGRect frame = self.view.frame;
//        frame.size.height -= height;
//        frame.origin.y -= height;
//        self.view.frame = frame;
//        NSLog(@"chat heigt ======= %f", height);
//
//        [self.tableView reloadData];
//    }

//    self.hidesBottomBarWhenPushed = YES;


    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = YES;
    //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
    baseY = self.view.frame.origin.y;




    // Do any additional setup after loading the view from its nib.
    [super viewDidLoad];

}
//
//- (void)hideTabBar {
//    if (self.tabBarController.tabBar.hidden == YES) {
//        return;
//
//    }
//    UIView *contentView;
//    if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
//        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
//    else
//        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
//    contentView.frame = CGRectMake(contentView.bounds.origin.x, contentView.bounds.origin.y, contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
//    self.tabBarController.tabBar.hidden = YES;
//
//}


- (void)viewDidAppear:(BOOL)animated {
    if(!isShow){
        [self scrollToLast];
        isShow = YES;
    }

    [delegate conversationUpdated:self];
    [super viewDidAppear:animated];
}

- (void)viewWillAppear:(BOOL)animated {


//    self.tabBarController.tabBar.hidden = YES;

//    [self hideTabBar];




    //键盘弹起的通知, 使用UIKeyboardWillShowNotification更加平滑
    [[NSNotificationCenter defaultCenter]
            addObserver:self
               selector:@selector(keyboardDidShow:)
                   name:UIKeyboardWillShowNotification
                 object:self.view.window];

    //键盘隐藏的通知
    [[NSNotificationCenter defaultCenter]
            addObserver:self
               selector:@selector(keyboardDidHide:)
                   name:UIKeyboardWillHideNotification
                 object:nil];

    //键盘弹起的通知
//    [[NSNotificationCenter defaultCenter]
//            addObserver:self
//               selector:@selector(keyboardDidShow:)
//                   name:UIKeyboardDidShowNotification
//                 object:self.view.window];


//     //键盘隐藏的通知
//    [[NSNotificationCenter defaultCenter]
//            addObserver:self
//               selector:@selector(keyboardDidHide:)
//                   name:UIKeyboardDidHideNotification
//                 object:nil];
}

/*
虽然解决了隐藏系统TabBar,显示自定义的TabBar并且视图不会错位的问题。但是不明白原理。希望高手解答一下。或是有什么另外的方法。

PS：用以上的方法隐藏系统TabBar，在需要显示系统的TabBar的时候要另外设置
*/
//- (void)showTabBar
//{
//    if (self.tabBarController.tabBar.hidden == NO)
//    {
//        return;
//    }
//    UIView *contentView;
//    if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
//
//        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
//
//    else
//
//        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
//    contentView.frame = CGRectMake(contentView.bounds.origin.x, contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
//    self.tabBarController.tabBar.hidden = NO;
//
//}

- (void)viewDidDisappear:(BOOL)animated {
//    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [self hideKeyboard:self.messageTextField];// 隐藏键盘，防止下次打开时遮住输入框

//    self.tabBarController.tabBar.hidden = NO;
//    [self showTabBar];

    [[NSNotificationCenter defaultCenter]
            removeObserver:self
                      name:UIKeyboardDidShowNotification
                    object:nil];

    [[NSNotificationCenter defaultCenter]
            removeObserver:self
                      name:UIKeyboardDidHideNotification
                    object:nil];
}

- (void)keyboardHide:(UITapGestureRecognizer *)tap {
    [self hideKeyboard:self.messageTextField];
}

/**
* 点击return时隐藏键盘
*/
- (IBAction)hideKeyboard:(id)sender {
    [sender resignFirstResponder];
//    if(!keyboardIsShown && !isFrameMove){
//        return;
//    }

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y = baseY;

//    currentKeyBoardHeight = 0;
//    viewFrame.origin.y -= keyboardRect.size.height;
    self.view.frame = viewFrame;
//    keyboardIsShown = NO;
//    isFrameMove = NO;


}

+ (NSMapTable *)chatRooms {
    return chatRooms;
}

- (IBAction)editDidEnd:(id)sender {
    [self hideKeyboard:sender];
}


/**
* 点击空白时隐藏键盘
*/
- (IBAction)backViewTouch:(id)sender {
    NSLog(@"touch -------- ");
    // 发送resignFirstResponder.
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}

//键盘弹起后处理scrollView的高度使得textfield可见
- (void)keyboardDidShow:(NSNotification *)notification {
//    NSLog(@"show~~~~~%@", keyboardIsShown);
//    if (keyboardIsShown && isFrameMove) {
//        return;
//    }
    NSDictionary *info = [notification userInfo];
    NSValue *avalue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [self.view convertRect:[avalue CGRectValue] fromView:nil];
    CGRect viewFrame = self.view.frame;
    float currentKeyBoardHeight = keyboardRect.size.height;
    viewFrame.origin.y = baseY - currentKeyBoardHeight;
    self.view.frame = viewFrame;

//    keyboardIsShown = YES;
//    isFrameMove = YES;
}

//键盘隐藏后处理scrollview的高度，使其还原为本来的高度
- (void)keyboardDidHide:(NSNotification *)notification {
    NSLog(@"hide~~~~~");
//    if(!keyboardIsShown && !isFrameMove){
//        return;
//    }


//    CGRect viewFrame = [_scrollView frame];
//    viewFrame.origin.y += keyboardRect.size.height;
//    _scrollView.frame = viewFrame;

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y = baseY;

//    currentKeyBoardHeight = 0;
//    viewFrame.origin.y -= keyboardRect.size.height;
    self.view.frame = viewFrame;

//    self.messageTextField.frame.origin.y -= keyboardRect.size.height;

//    isFrameMove = NO;
//    keyboardIsShown = NO;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textFieldView {
    [textFieldView resignFirstResponder];
    return NO;
}


- (void)textFieldDidEndEditing:(UITextField *)textFieldView {
//    currentTextField = nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sendMessage:(id)sender {
    NSString *messageBody = self.messageTextField.text;
    if (messageBody != nil && ![[messageBody stringByTrimming] isEqualToString:@""]) {
        XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.withUser.jid];
        [message addBody:messageBody];

        [[[KRAppDelegate appDelegate] xmppStream] sendElement:message];
        self.messageTextField.text = @"";
        [self checkMessageField];
    }
}

- (void)checkMessageField{
    NSString *messageBody = self.messageTextField.text;
    if(messageBody != nil && ![[messageBody stringByTrimming] isEqualToString:@""]){
        self.sendMessageButton.enabled = YES;
    } else {
        self.sendMessageButton.enabled = NO;
    }

}

- (IBAction)messageDidEnd:(id)sender {
    [self sendMessage:sender];
}

- (IBAction)messageChanged:(id)sender {
    [self checkMessageField];
}

+ (void)setDelegate:(id <KRChatViewControllerDelegate>)targetDelegate {
    delegate = targetDelegate;
}


/**
 * XEP-0136
 */
- (NSFetchedResultsController *)fetchedResultsController {
    if (fetchedResultsController == nil) {
        NSManagedObjectContext *moc = [[KRAppDelegate appDelegate] managedObjectContext_message];

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject"
                                                  inManagedObjectContext:moc];

        NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:NO];
//        NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bareJidStr = %@", self.withUser.jidStr];//相当于select中的查询条件


        NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, nil];

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:entity];
        [fetchRequest setPredicate:predicate];

        [fetchRequest setSortDescriptors:sortDescriptors];
        [fetchRequest setFetchBatchSize:10];
        [fetchRequest setFetchLimit:20];


        fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                       managedObjectContext:moc
                                                                         sectionNameKeyPath:@"timestamp"
                                                                                  cacheName:nil];
        [fetchedResultsController setDelegate:self];


        NSError *error = nil;
        if (![fetchedResultsController performFetch:&error]) {
            DDLogError(@"Error performing fetch: %@", error);
        }

    }

    return fetchedResultsController;
}

- (void)scrollToLast {
    [self.tableView scrollBubbleViewToBottomAnimated:true];
//    NSIndexPath *lastRow = [NSIndexPath indexPathForRow:([self rowsForBubbleTable:self.tableView]) inSection:0];
//    @try {
//        [[self tableView] scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:true];
//    }
//    @catch(NSException *e){
//        NSLog(@"Exception: %@", e);
//    }


}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [[self tableView] reloadData];
    [self scrollToLast];
    [delegate conversationUpdated:self];
}


- (NSInteger)rowsForBubbleTable:(UIBubbleTableView *)tableView {
    NSArray *result = [[self fetchedResultsController] fetchedObjects];
    if (result) {
        return result.count;
    }
    return 0;
}

- (NSBubbleData *)bubbleTableView:(UIBubbleTableView *)tableView dataForRow:(NSInteger)row {
    NSArray *result = [self fetchedResultsController].fetchedObjects;
    if (result) {
        int index = result.count - row - 1;// 反向排序，使得最近会话在最底端

        XMPPMessageArchiving_Message_CoreDataObject *message = [result objectAtIndex:index];
        NSBubbleType bubbleType = BubbleTypeMine;
        if (!message.isOutgoing) {
            bubbleType = BubbleTypeSomeoneElse;
        }
        NSBubbleData *data = [[NSBubbleData alloc] initWithText:message.body date:message.timestamp type:bubbleType];
        return data;
    }
    return nil;
}


@end
